/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MenuPanel.java
 *
 * Created on 1.4.2009, 21:44:18
 */

package jmenu.gui;

import java.io.File;
import javax.xml.transform.TransformerException;
import org.w3c.dom.*;
import javax.xml.xpath.*;
import javax.xml.parsers.*;
import java.io.IOException;
import javax.swing.JOptionPane;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import jmenu.dbmodels.MSectionsOfFood;
import jmenu.main.Config;
import jmenu.main.FitnessTools;
import jmenu.main.Time;
import org.xml.sax.SAXException;


/**
 *
 * @author sevcik.roman
 */
public class MenuPanel extends javax.swing.JPanel {

    MealPanel [] mealpanel;

    MSectionsOfFood sections;

    /** Creates new form MenuPanel */
    public MenuPanel()
    {
        
        this.sections = Config.getKernel().queries.loadAllSectionOfFoodOrderBySectionId();

        initComponents();

        this.mealPanel1.setTime(new Time(7,0));
        this.mealPanel2.setTime(new Time(9,0));
        this.mealPanel3.setTime(new Time(11,30));
        this.mealPanel4.setTime(new Time(14,0));
        this.mealPanel5.setTime(new Time(16,30));
        this.mealPanel6.setTime(new Time(19,0));
        this.mealPanel7.setTime(new Time(21,0));

        this.mealpanel = new MealPanel[7];

        this.mealpanel[0] = this.mealPanel1;
        this.mealpanel[1] = this.mealPanel2;
        this.mealpanel[2] = this.mealPanel3;
        this.mealpanel[3] = this.mealPanel4;
        this.mealpanel[4] = this.mealPanel5;
        this.mealpanel[5] = this.mealPanel6;
        this.mealpanel[6] = this.mealPanel7;
        
    }

    public void setRecomendedData(double e, double b, double s, double t)
    {
        double [] data;

        for (int i = 0; i < 7; i++)
        {
            data = FitnessTools.getRatioOfMeal(i + 1, b, s);
            this.mealpanel[i].setRecomendedData(0, data[0], data[1], 0);
        }
    }

    /**
     * Same menu to file
     * @param file
     * @return true if file was saved
     */
    public boolean saveToFile(File file)
    {        
        try
        {
            if (!file.createNewFile())
                if (!file.canWrite())
                {
                    JOptionPane.showMessageDialog(Config.getMainFrame(), "Nelze zapisovat do souboru!");
                    return false;
                }

        } catch (IOException ex)
        {
            JOptionPane.showMessageDialog(Config.getMainFrame(), "Chyba při zápisu do souboru: "+ ex.getMessage() );
            return false;
        }

        try
        {        
            DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true);
            DocumentBuilder builder = domFactory.newDocumentBuilder();

            Document document = builder.newDocument();

            Element jmenu = document.createElement("jmenu");
            document.appendChild(jmenu);
            //start element menu
            Element menu = document.createElement("menu");
            //start element menu

            Element meal;
            Element time;
            Element hours;
            Element minutes;

            Element foodstuff;
            Element category;
            Element food;
            Element amount;

            for(int h = 1; h <= 7; h++)
            {       
                meal = document.createElement("meal"+String.valueOf(h));
                //start element time
                time = document.createElement("time");
                hours = document.createElement("hours");
                hours.appendChild(document.createTextNode(String.valueOf(this.mealpanel[h - 1].getTime().getHours())));
                time.appendChild(hours);
                minutes = document.createElement("minutes");
                minutes.appendChild(document.createTextNode(String.valueOf(this.mealpanel[h - 1].getTime().getMinutes())));
                time.appendChild(minutes);
                //end element time
                meal.appendChild(time);

                for(int i = 1; i <= 5; i++)
                {
                    //start element food
                    foodstuff = document.createElement("foodstuff"+String.valueOf(i));

                    category = document.createElement("category");
                    category.appendChild(document.createTextNode(String.valueOf(this.mealpanel[h - 1].getFoodData()[i - 1][0])));
                    foodstuff.appendChild(category);
                
                    food = document.createElement("food");
                    food.appendChild(document.createTextNode(String.valueOf(this.mealpanel[h - 1].getFoodData()[i - 1][1])));
                    foodstuff.appendChild(food);

                    amount = document.createElement("amount");
                    amount.appendChild(document.createTextNode(String.valueOf(this.mealpanel[h - 1].getFoodData()[i - 1][2])));
                    foodstuff.appendChild(amount);

                    //end element food
                    meal.appendChild(foodstuff);
                }
                //end elemetn meal
                menu.appendChild(meal);
            }

            //end element menu
            jmenu.appendChild(menu);

            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();

            DOMSource source = new DOMSource(document);
            StreamResult result = new StreamResult(file);

            transformer.transform(source, result);
        }
        catch (ParserConfigurationException ex){return false;}
        catch (TransformerException ex){return false;}

        return true;
    }


    public boolean  loadFromFile(File file)
    {
        try
        {
            DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true);
            DocumentBuilder builder = domFactory.newDocumentBuilder();

            Document doc = builder.parse(file);
            XPath xpath = XPathFactory.newInstance().newXPath();

            XPathExpression expr;
            Object result;
            NodeList node;
            int hours;
            int minutes;
            int [][] foodStuff;

            for(int h = 1; h <= 7; h++)
            {
                hours = -1;
                minutes = -1;

            //load time
            expr = xpath.compile("//jmenu/menu/meal"+String.valueOf(h)+"/time/hours/text()");
            result = expr.evaluate(doc, XPathConstants.NODESET);
            node = (NodeList) result;
            if (node.getLength() == 1)
                try
                {
                    hours = Integer.valueOf(node.item(0).getNodeValue());
                }catch (NumberFormatException ex) {}
            else
                hours = 0;

            expr = xpath.compile("//jmenu/menu/meal"+String.valueOf(h)+"/time/minutes/text()");
            result = expr.evaluate(doc, XPathConstants.NODESET);
            node = (NodeList) result;
            if (node.getLength() == 1)
                try
                {
                    minutes = Integer.valueOf(node.item(0).getNodeValue());
                }catch (NumberFormatException ex) {}
            else
                minutes = 0;

            if (hours != -1 && minutes != -1 )
                this.mealpanel[h - 1].setTime(new Time(hours, minutes));

            foodStuff = new int [5][3];

            for(int j = 1; j <= 5; j++)
            {
                expr = xpath.compile("//jmenu/menu/meal"+String.valueOf(h)+"/foodstuff"+String.valueOf(j)+"/category/text()");
                result = expr.evaluate(doc, XPathConstants.NODESET);
                node = (NodeList) result;
                if (node.getLength() == 1)
                try
                {
                    foodStuff[j - 1][0] = Integer.valueOf(node.item(0).getNodeValue());
                }catch (NumberFormatException ex) {}
                else
                    foodStuff[j - 1][0] = 0;

                expr = xpath.compile("//jmenu/menu/meal"+String.valueOf(h)+"/foodstuff"+String.valueOf(j)+"/food/text()");
                result = expr.evaluate(doc, XPathConstants.NODESET);
                node = (NodeList) result;
                if (node.getLength() == 1)
                try
                {
                    foodStuff[j - 1][1] = Integer.valueOf(node.item(0).getNodeValue());
                }catch (NumberFormatException ex) {}
                else
                    foodStuff[j - 1][1] = 0;

                expr = xpath.compile("//jmenu/menu/meal"+String.valueOf(h)+"/foodstuff"+String.valueOf(j)+"/amount/text()");
                result = expr.evaluate(doc, XPathConstants.NODESET);
                node = (NodeList) result;
                if (node.getLength() == 1)
                try
                {
                    foodStuff[j - 1][2] = Integer.valueOf(node.item(0).getNodeValue());
                }catch (NumberFormatException ex) {}
                else
                    foodStuff[j - 1][2] = 0;
                
            }

            this.mealpanel[h - 1].setFoodData(foodStuff);


            //load time
            //expr = xpath.compile("//jmenu/menu/meal"+String.valueOf(h)+"/minutes/text()");
            //result = expr.evaluate(doc, XPathConstants.NODESET);
            //node = (NodeList) result;
            //if (node.getLength() == 1)
            //    try
            //    {
            //        this.locX = Integer.valueOf(node.item(0).getNodeValue());
            //    }catch (NumberFormatException ex) {}
            }
        }
        catch (IOException ex)
        {return false;}
        catch (ParserConfigurationException ex)
        {return false;}
        catch (SAXException ex)
        {return false;}
        catch (XPathExpressionException ex)
        {return false;}

        return true;
    }

    public String [][][] getExportData()
    {
        String [][][] Summary = new String[7][][];

        Summary[0] = this.mealPanel1.getExportData();
	Summary[1] = this.mealPanel2.getExportData();
	Summary[2] = this.mealPanel3.getExportData();
	Summary[3] = this.mealPanel4.getExportData();
	Summary[4] = this.mealPanel5.getExportData();
	Summary[5] = this.mealPanel6.getExportData();
	Summary[6] = this.mealPanel7.getExportData();
                         
        return Summary;
    }

    public double [] getSummaryData()
    {
        double [] Summary = new double[5];

        for(int j = 0; j < 5;j++)
        {
            Summary[j] = 0.0;
            Summary[j] = this.mealPanel1.getSummaryData()[j] +
                         this.mealPanel2.getSummaryData()[j] +
                         this.mealPanel3.getSummaryData()[j] +
                         this.mealPanel4.getSummaryData()[j] +
                         this.mealPanel5.getSummaryData()[j] +
                         this.mealPanel6.getSummaryData()[j] +
                         this.mealPanel7.getSummaryData()[j];
        }
        return Summary;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jPanel1 = new javax.swing.JPanel();
        mealPanel1 = new jmenu.gui.MealPanel(this.sections);
        mealPanel2 = new jmenu.gui.MealPanel(this.sections);
        mealPanel3 = new jmenu.gui.MealPanel(this.sections);
        mealPanel4 = new jmenu.gui.MealPanel(this.sections);
        mealPanel5 = new jmenu.gui.MealPanel(this.sections);
        mealPanel6 = new jmenu.gui.MealPanel(this.sections);
        mealPanel7 = new jmenu.gui.MealPanel(this.sections);

        setPreferredSize(new java.awt.Dimension(810, 2009));

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N
        jPanel1.setPreferredSize(new java.awt.Dimension(810, 2007));

        mealPanel1.setName("mealPanel1"); // NOI18N

        mealPanel2.setName("mealPanel2"); // NOI18N

        mealPanel3.setName("mealPanel3"); // NOI18N

        mealPanel4.setName("mealPanel4"); // NOI18N

        mealPanel5.setName("mealPanel5"); // NOI18N

        mealPanel6.setName("mealPanel6"); // NOI18N

        mealPanel7.setName("mealPanel7"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mealPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(mealPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(mealPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(mealPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(mealPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                .addComponent(mealPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(mealPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(mealPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(mealPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(mealPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(mealPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(mealPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(mealPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(mealPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(81, Short.MAX_VALUE))
        );

        jScrollPane1.setViewportView(jPanel1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 810, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 2009, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private jmenu.gui.MealPanel mealPanel1;
    private jmenu.gui.MealPanel mealPanel2;
    private jmenu.gui.MealPanel mealPanel3;
    private jmenu.gui.MealPanel mealPanel4;
    private jmenu.gui.MealPanel mealPanel5;
    private jmenu.gui.MealPanel mealPanel6;
    private jmenu.gui.MealPanel mealPanel7;
    // End of variables declaration//GEN-END:variables

}
